package miniproj.services.data;

import java.io.File;

import javax.xml.bind.*;

/**
 * This class is able to serialize data in a XML format using the JAXB library.
 * 
 * @author Baptiste Viale
 * 
 */
public class XMLDataWriter implements DataWriter {

	private String folderPath;

	/**
	 * Instantiates a new xML data writer.
	 * 
	 * @param folderPath
	 *            the folder path
	 */
	public XMLDataWriter(String folderPath) {
		this.folderPath = folderPath;
	}

	/**
	 * Serialize the DataContext using the XML format.
	 * 
	 * @param dc
	 *            the data context to be serialized
	 * @param dataContextFileName
	 *            the data context file name
	 */
	@Override
	public void setDataContext(DataContext dc, String dataContextFileName) {
		try {
			JAXBContext jc = JAXBContext.newInstance(DataContext.class);

			Marshaller m = jc.createMarshaller();
			m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

			m.marshal(dc, new File(folderPath + "/" + dataContextFileName));
		} catch (JAXBException e) {
			System.err.println("Failed to store data : " + e.getMessage());
		}
	}
}
